package cn.fl.inscare.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import cmm.mid.core.framework.page.DataResultVO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.inscare.service.IInsUploadFileService;
import cn.fl.inscare.vo.FileAttrVO;
import cn.fl.inscare.vo.UploadIdentityVO;

/**
 * 文件上传controller
 */
@Controller
@RequestMapping(value = "/inscare/upload", method = RequestMethod.POST)
public class InsUploadFileController extends BaseConstant {
    private static final Logger logger = LoggerFactory.getLogger(InsUploadFileController.class);
    private static final String FILE_NAME = "files";
    @Autowired
    private IInsUploadFileService insUploadFileService;

    /**
     * 上传身份证图片
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "uploadIdentity.do", method = RequestMethod.POST)
    @ResponseBody
    public DataResultVO uploadIdentity(HttpServletRequest request) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "上传成功");
        String applyId = request.getParameter("applyId");
        String name = request.getParameter("name");
        String code = request.getParameter("code");
        List<FileAttrVO> fileAttr = new ArrayList<FileAttrVO>();
        FileAttrVO fileAttrVO = new FileAttrVO();
        fileAttrVO.setCode(code);
        fileAttrVO.setName(name);
        fileAttr.add(fileAttrVO);
        UploadIdentityVO uiVo = new UploadIdentityVO();
        uiVo.setApplyId(Long.valueOf(applyId));
        uiVo.setFileAttrs(fileAttr);
        
        if (uiVo == null || uiVo.getApplyId() == null || uiVo.getApplyId() <= 0) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("保险申请信息id不是有效值");
            return result;
        }
        
        try {

            DataResultVO dataResultVO = checkUploadFiles(request, "没有可以获取到上传的身份证图片文件");
            if (dataResultVO != null) {
                return dataResultVO;
            }
            boolean isSuccess = this.insUploadFileService.uploadIdentity(request, uiVo);
            if (!isSuccess) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("上传身份证图片失败");
                logger.info("上传身份证图片失败");
            }
        } catch (BaseException be) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(be.toString());
            logger.info("上传身份证图片发生异常", be);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.toString());
            logger.info("上传身份证图片发生异常", ex);
        }

        return result;
    }

 /*   *//**
     * 上传批单图片
     *
     * @param request
     * @return
     *//*
    @RequestMapping(value = "uploadEndorsement.do", method = RequestMethod.POST)
    @ResponseBody
    public DataResultVO uploadEndorsement(HttpServletRequest request) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "上传成功");
        String applyId = request.getParameter("applyId");
    	String name = request.getParameter("name");
    	String code = request.getParameter("code");
    	String sequenceNum=request.getParameter("seq");
    	List<FileAttrVO> fileAttr = new ArrayList<FileAttrVO>();
    	FileAttrVO fileAttrVO = new FileAttrVO();
    	fileAttrVO.setCode(code);
    	fileAttrVO.setName(name);
    	fileAttr.add(fileAttrVO);
    	UploadIdentityVO uiVo = new UploadIdentityVO();
    	uiVo.setApplyId(Long.valueOf(applyId));
    	uiVo.setFileAttrs(fileAttr);
        if (uiVo == null || uiVo.getApplyId() == null || uiVo.getApplyId() <= 0) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("保险申请信息id不是有效值");
            return result;
        }
        try {
            DataResultVO dataResultVO = checkUploadFiles(request, "没有可以获取到上传的批单图片文件");
            if (dataResultVO != null) {
                return dataResultVO;
            }
            boolean isSuccess = this.insUploadFileService.uploadEndorsement(request, uiVo,Integer.parseInt(sequenceNum));
            if (!isSuccess) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("上传批单图片失败");
                logger.info("上传批单图片失败");
            }
        } catch (BaseException be) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(be.toString());
            logger.info("上传批单图片发生异常", be);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.toString());
            logger.info("上传批单图片发生异常", ex);
        }

        return result;
    }
    
    *//**
     * 上传行驶证图片
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "uploadInsVehLice.do", method = RequestMethod.POST)
    @ResponseBody
    public DataResultVO uploadInsVehLice(HttpServletRequest request) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "上传成功");
        String applyId = request.getParameter("applyId");
        String name = request.getParameter("name");
        String code = request.getParameter("code");
        List<FileAttrVO> fileAttr = new ArrayList<FileAttrVO>();
        FileAttrVO fileAttrVO = new FileAttrVO();
        fileAttrVO.setCode(code);
        fileAttrVO.setName(name);
        fileAttr.add(fileAttrVO);
        UploadIdentityVO uiVo = new UploadIdentityVO();
        uiVo.setApplyId(Long.valueOf(applyId));
        uiVo.setFileAttrs(fileAttr);
        
        if (uiVo == null || uiVo.getApplyId() == null || uiVo.getApplyId() <= 0) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("保险申请信息id不是有效值");
            return result;
        }
        
        try {
            DataResultVO dataResultVO = checkUploadFiles(request, "没有可以获取到上传的行驶证图片文件");
            if (dataResultVO != null) {
                return dataResultVO;
            }
            boolean isSuccess = this.insUploadFileService.uploadInsVehLice(request, uiVo);
            if (!isSuccess) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("上传行驶证图片失败");
                logger.info("上传行驶证图片失败");
            }
        } catch (BaseException be) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(be.toString());
            logger.info("上传行驶证图片发生异常", be);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.toString());
            logger.info("上传行驶证图片发生异常", ex);
        }

        return result;
    }
    
    /**
     * 上传营业执照图片
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "uploadInsApplyBuss.do", method = RequestMethod.POST)
    @ResponseBody
    public DataResultVO uploadInsApplyBuss(HttpServletRequest request) {
    	DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "上传成功");
    	String applyId = request.getParameter("applyId");
    	String name = request.getParameter("name");
    	String code = request.getParameter("code");
    	List<FileAttrVO> fileAttr = new ArrayList<FileAttrVO>();
    	FileAttrVO fileAttrVO = new FileAttrVO();
    	fileAttrVO.setCode(code);
    	fileAttrVO.setName(name);
    	fileAttr.add(fileAttrVO);
    	UploadIdentityVO uiVo = new UploadIdentityVO();
    	uiVo.setApplyId(Long.valueOf(applyId));
    	uiVo.setFileAttrs(fileAttr);
    	
    	if (uiVo == null || uiVo.getApplyId() == null || uiVo.getApplyId() <= 0) {
    		result.setSuccess(BaseConstant.IS_YESNO_NO);
    		result.setInfo("保险申请信息id不是有效值");
    		return result;
    	}
    	
    	try {
            DataResultVO dataResultVO = checkUploadFiles(request, "没有可以获取到上传的营业执照图片文件");
            if (dataResultVO != null) {
                return dataResultVO;
            }
    		boolean isSuccess = this.insUploadFileService.uploadInsApplyBuss(request, uiVo);
    		if (!isSuccess) {
    			result.setSuccess(BaseConstant.IS_YESNO_NO);
    			result.setInfo("上传营业执照图片失败");
    			logger.info("上传营业执照图片失败");
    		}
    	} catch (BaseException be) {
    		result.setSuccess(BaseConstant.IS_YESNO_NO);
    		result.setInfo(be.toString());
    		logger.info("上传营业执照图片发生异常", be);
    	} catch (Exception ex) {
    		result.setSuccess(BaseConstant.IS_YESNO_NO);
    		result.setInfo(ex.toString());
    		logger.info("上传营业执照图片发生异常", ex);
    	}
    	return result;
    }
    /**
     * 上传投保单图片
     *
     * @param request
     * @return
     */
	@RequestMapping(value = "uploadInsApply.do", method = RequestMethod.POST)
    @ResponseBody
    public DataResultVO uploadInsApply(HttpServletRequest request,String[] name) {
    	DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "上传成功");
    	String applyId = request.getParameter("applyId");
    	
    	String code = request.getParameter("code");
    	List<FileAttrVO> fileAttr = new ArrayList<FileAttrVO>();
    	for (int i = 0; i < name.length; i++) {
    		FileAttrVO fileAttrVO = new FileAttrVO();
    		fileAttrVO.setCode(code);
    		fileAttrVO.setName(name[i]);
    		fileAttr.add(fileAttrVO);
		}
    	UploadIdentityVO uiVo = new UploadIdentityVO();
    	uiVo.setApplyId(Long.valueOf(applyId));
    	uiVo.setFileAttrs(fileAttr);
    	
    	 MultipartHttpServletRequest multipartRequest = null;
         if (request instanceof MultipartHttpServletRequest) {
             multipartRequest = (MultipartHttpServletRequest) request;
             List<MultipartFile> files = multipartRequest.getFiles(FILE_NAME);
             if (CollectionUtils.isNotEmpty(files)) {
            	 if(files.size() > 2){
            		 result.setSuccess(BaseConstant.IS_YESNO_NO);
             	 	 result.setInfo("投保单最多上传两张图片");
             	 	 return result;
            	 }
            	 	
             }
         }
    	
    	
    	if (uiVo == null || uiVo.getApplyId() == null || uiVo.getApplyId() <= 0) {
    		result.setSuccess(BaseConstant.IS_YESNO_NO);
    		result.setInfo("保险申请信息id不是有效值");
    		return result;
    	}
    	
    	try {
            DataResultVO dataResultVO = checkUploadFiles(request, "没有可以获取到上传的上传保单明细图片文件");
            if (dataResultVO != null) {
                return dataResultVO;
            }
    		boolean isSuccess = this.insUploadFileService.uploadInsApply(request, uiVo);
    		if (!isSuccess) {
    			result.setSuccess(BaseConstant.IS_YESNO_NO);
    			result.setInfo("上传投保单图片失败");
    			logger.info("上传投保单图片失败");
    		}
    	} catch (BaseException be) {
    		result.setSuccess(BaseConstant.IS_YESNO_NO);
    		result.setInfo(be.toString());
    		logger.info("上传投保单图片发生异常", be);
    	} catch (Exception ex) {
    		result.setSuccess(BaseConstant.IS_YESNO_NO);
    		result.setInfo(ex.toString());
    		logger.info("上传投保单图片发生异常", ex);
    	}
    	return result;
    }

    /**
     * 检查是否有上传文件
     *
     * @param request
     * @param retMsg
     * @return
     */
    private DataResultVO checkUploadFiles(HttpServletRequest request, String retMsg) {
        DataResultVO result = null;
        MultipartHttpServletRequest multipartRequest = null;
        if (request instanceof MultipartHttpServletRequest) {
            multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> files = multipartRequest.getFiles(FILE_NAME);
            if (CollectionUtils.isEmpty(files)) {
                result = new DataResultVO(BaseConstant.IS_YESNO_NO, retMsg);
                return result;
            }
        } else {
            result = new DataResultVO(BaseConstant.IS_YESNO_NO, "request 不是 MultipartHttpServletRequest");
            return result;
        }

        String fileName = validImageFileExtension(multipartRequest);
        if (StringUtils.isNotEmpty(fileName)) {
            result = new DataResultVO(BaseConstant.IS_YESNO_NO, String.format("%s不是图片文件", fileName));
            return result;
        }

        return result;
    }

    /**
     * 验证图片扩展名
     *
     * @param multipartRequest
     * @return
     */
    private String validImageFileExtension(MultipartHttpServletRequest multipartRequest) {
//        String[] extensions = PropertiesCacheUtils.getProperty(UploadConstant.INS_IMAGE_EXTENSION).split(";");
        String[] extensions ={"jpg","png","bmp","jpeg"};
        for (MultipartFile file : multipartRequest.getFiles(FILE_NAME)) {
            if (!isImageFileEextension(file.getOriginalFilename(), extensions)) {
                return file.getOriginalFilename();
            }
        }
        return null;
    }

    /**
     * 验证文件扩展名是否是图片
     *
     * @param originalFilename
     * @param extensions
     * @return
     */
    private boolean isImageFileEextension(String originalFilename, String[] extensions) {
        for (String extension : extensions) {
            if (originalFilename.toLowerCase().endsWith(extension)) {
                return true;
            }
        }

        return false;
    }
    /**
     * 上传商业险、交强险保单
     *
     * @param request
     * @return
     *//*
    @RequestMapping(value = "uploadInsBusApply.do", method = RequestMethod.POST)
    @ResponseBody
    public DataResultVO uploadInsBusApply(HttpServletRequest request) {
    	DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "上传成功");
    	String applyId = request.getParameter("applyId");
    	String name = request.getParameter("name");
    	String code = request.getParameter("code");
    	List<FileAttrVO> fileAttr = new ArrayList<FileAttrVO>();
    	FileAttrVO fileAttrVO = new FileAttrVO();
    	fileAttrVO.setCode(code);
    	fileAttrVO.setName(name);
    	fileAttr.add(fileAttrVO);
    	UploadIdentityVO uiVo = new UploadIdentityVO();
    	uiVo.setApplyId(Long.valueOf(applyId));
    	uiVo.setFileAttrs(fileAttr);
    	
    	if (uiVo == null || uiVo.getApplyId() == null || uiVo.getApplyId() <= 0) {
    		result.setSuccess(BaseConstant.IS_YESNO_NO);
    		result.setInfo("保险申请信息id不是有效值");
    		return result;
    	}
    	
    	try {
            DataResultVO dataResultVO = checkUploadFiles(request, "没有可以获取到上传的上传保单明细图片文件");
            if (dataResultVO != null) {
                return dataResultVO;
            }
    		boolean isSuccess = this.insUploadFileService.uploadInsBusApply(request, uiVo);
    		if (!isSuccess) {
    			result.setSuccess(BaseConstant.IS_YESNO_NO);
    			result.setInfo("上传投保单图片失败");
    			logger.info("上传投保单图片失败");
    		}
    	} catch (BaseException be) {
    		result.setSuccess(BaseConstant.IS_YESNO_NO);
    		result.setInfo(be.toString());
    		logger.info("上传投保单图片发生异常", be);
    	} catch (Exception ex) {
    		result.setSuccess(BaseConstant.IS_YESNO_NO);
    		result.setInfo(ex.toString());
    		logger.info("上传投保单图片发生异常", ex);
    	}
    	return result;
    }
    *//**
     * 上传保险公司Logo
     * @param request
     * @return
     *//*
    @RequestMapping(value = "uploadInsCompInfo.do", method = RequestMethod.POST)
    @ResponseBody
    public DataResultVO uploadInsCompInfo(HttpServletRequest request) {
    	DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "上传成功");
    	String applyId = request.getParameter("insCompId");
    	String name = request.getParameter("name");
    	String code = request.getParameter("code");
    	List<FileAttrVO> fileAttr = new ArrayList<FileAttrVO>();
    	FileAttrVO fileAttrVO = new FileAttrVO();
    	fileAttrVO.setCode(code);
    	fileAttrVO.setName(name);
    	fileAttr.add(fileAttrVO);
    	UploadIdentityVO uiVo = new UploadIdentityVO();
    	uiVo.setApplyId(Long.valueOf(applyId));
    	uiVo.setFileAttrs(fileAttr);

    	if (uiVo == null || uiVo.getApplyId() == null || uiVo.getApplyId() <= 0) {
    		result.setSuccess(BaseConstant.IS_YESNO_NO);
    		result.setInfo("id不是有效值");
    		return result;
    	}

    	try {
            DataResultVO dataResultVO = checkUploadFiles(request, "没有可以获取到上传的保险公司Logo图片文件");
            if (dataResultVO != null) {
                return dataResultVO;
            }
    		boolean isSuccess = this.insUploadFileService.uploadInsCompInfo(request, uiVo);
    		if (!isSuccess) {
    			result.setSuccess(BaseConstant.IS_YESNO_NO);
    			result.setInfo("上传保险公司Logo图片失败");
    			logger.info("上传保险公司Logo图片失败");
    		}
    	} catch (BaseException be) {
    		result.setSuccess(BaseConstant.IS_YESNO_NO);
    		result.setInfo(be.toString());
    		logger.info("上传保险公司Logo图片发生异常", be);
    	} catch (Exception ex) {
    		result.setSuccess(BaseConstant.IS_YESNO_NO);
    		result.setInfo(ex.toString());
    		logger.info("上传保险公司Logo图片发生异常", ex);
    	}
    	return result;
    }*/
}
